<!-- 起草合同 -->
<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew title="编辑起草合同" showBack> </pageHeaderNew>
    </template>
    <div class="template-steps">
      <a-steps @change="changeCurrent" :current="current" style="width: 700px">
        <a-step v-for="item in stepData" :key="item.id">{{ item.name }}</a-step>
      </a-steps>
    </div>
    <div>
      <div v-show="currentComponents === 'Step1'">
        <Step1 ref="refStep1" @changeStepData="changeStepData" />
      </div>
      <div v-show="currentComponents === 'Step2'">
        <Step2 ref="refStep2" />
      </div>
      <div v-show="currentComponents === 'Step3'">
        <Step3 :userList="userList" :templateList="temList" :templateObj="temObj" />
      </div>
      <div v-show="currentComponents === 'Step4'">
        <Step4 ref="refStep4" />
      </div>
    </div>

    <footer>
      <a-space>
        <a-button type="secondary" :disabled="current <= 1" @click="onPrev">
          <IconLeft />
          上一步
        </a-button>
        <a-button type="primary" v-show="current !== stepData.length" :disabled="current >= stepData.length" @click="onNext">
          下一步
          <IconRight />
        </a-button>
        <a-button type="outline" v-show="current === stepData.length" @click="save(false)">
          保存
        </a-button>
        <a-button type="secondary" @click="router.back()"> 取消 </a-button>
        <a-button type="outline" v-show="current === stepData.length" @click="save(true)">
          提交
        </a-button>
      </a-space>
    </footer>
  </ContentCard>
</template>

<script setup lang="ts">
import {
  SwitchDraftWaitSignedContract,
  DraftWaitSignedContractSave,
  GetGenerateContractNum,
  DraftWaitSignedContractSavePut,
  GetUserContractByStatusDetail,
  ChangeWaitSignedContractState,
  DraftWaitSignedContractSavePutStatus
} from '@/apis/management/contract/contractManagement/waitSigned';

import dayjs from 'dayjs';
import { ref } from 'vue';
import Step1 from './components/Step1.vue';
import Step2 from './components/Step2.vue';
import Step3 from './components/Step3.vue';
import Step4 from './components/Step4.vue';
const route: any = useRoute();
const router = useRouter();
const userId = +route.query.userId;

let refStep1 = ref();
let refStep2 = ref();
let refStep4 = ref();

const type2 = [
  { id: 1, name: '合同信息', components: 'Step1' },
  { id: 2, name: '合同编辑', components: 'Step2' },
  { id: 3, name: '合同预览', components: 'Step3' },
  { id: 4, name: '合同签署', components: 'Step4' }
];
const type1 = [
  { id: 1, name: '合同信息', components: 'Step1' },
  { id: 2, name: '合同预览', components: 'Step3' },
  { id: 3, name: '合同签署', components: 'Step4' }
];

const stepData = ref(type1);

const current = ref(1);
const onPrev = () => {
  current.value--;
  currentComponents.value = stepData.value[current.value - 1].components;
};
const currentComponents = ref('Step1');
const changeCurrent = (e) => {};
let temObj = reactive<any>({});
let temList = ref<any[]>([]);
let userList = ref<any[]>([]);
let formData = reactive<any>({});
let idData = ref(0);
// ---------------------------------------------------方法
// 获取起草合同详情
const getContractData = async () => {
  try {
    const res = await GetUserContractByStatusDetail({
      userId: userId,
      status: 1
    });
    // 最新的一条
    let data = res[res.length - 1];
    return data;
  } catch (error: unknown) {
    console.log('获取起草合同详情', error);
  }
};
// 下一步
const onNext = async () => {
  //提取第一步数据塞到第二步
  if (current.value === 1) {
    let { form, templateList, userInfo } = await refStep1.value.getData();
    console.log('ref1的数据=》', form, templateList, userInfo);
    // console.log('ref1的数据=》', templateList);
    // return;
    for (const key in formData) {
      delete formData[key];
    }
    temList.value = [];
    temObj.value = [];
    Object.assign(formData, form);
    // 这是合同模版
    if (form.contractTemplateType === 2) {
      let templateObj: any = {};
      userInfo.forEach(({ id, name }: any) => {
        templateList.forEach((item: any) => {
          templateObj[id + '-' + item.uuid] = {
            userInfo: {
              id: id,
              name: name
            },
            name: item.name,
            text: item.text,
            codes: item.codes,
            logo: item.logo,
            style: item.style,
            typeId: item.typeId,
            enterpriseName: item.enterpriseName
          };
        });
      });
      refStep2.value.setData({
        templateObj,
        templateList,
        users: userInfo
      });
    } else if (form.contractTemplateType === 1) {
      userList.value = userInfo;
      let templateObj: any = {};
      userInfo.forEach(({ id, name }: any) => {
        templateList.forEach((item: any) => {
          if (item.codes) {
            templateObj[id + '-' + item.uuid] = {
              userInfo: {
                id: id,
                name: name
              },
              name: item.name,
              text: item.text,
              codes: item.codes,
              logo: item.logo,
              style: item.style,
              typeId: item.typeId,
              enterpriseName: item.enterpriseName
            };
          } else {
            templateObj[id + '-' + item.uuid] = {
              // id: item.id,
              // fileName: item.fileName,
              // fileUrl: item.fileUrl,
              // uuid: item.uuid,
              // name: item.fileName,
              ...item,
              userInfo: {
                id: id,
                name: name
              }
            };
          }
        });
      });
      temList.value = templateList;
      for (const key in temObj) {
        delete temObj[key];
      }
      Object.assign(temObj, templateObj);
    }
    // 跳转2
  } else if (
    current.value === 2 &&
    stepData.value[current.value - 1].name === '合同编辑'
  ) {
    let data = await refStep2.value.getData();
    temList.value = data.templateList;
    userList.value = data.userList;
    for (const key in temObj) {
      delete temObj[key];
    }
    Object.assign(temObj, data.templateObj);
  }
  current.value++;
  currentComponents.value = stepData.value[current.value - 1].components;
};

const getTemList = (user: any) => {
  let newAddr = [];
  temList.value.forEach((item) => {
    let tem = temObj[user.id + '-' + item.uuid];
    const newKey = Object.keys(item);
    if (newKey.includes('codes'))
      newAddr.push({
        userInfo: {
          id: user.id,
          name: user.name
        },
        name: item.name,
        text: tem.text,
        codes: tem.codes,
        logo: tem.logo,
        style: tem.style,
        typeId: tem.typeId,
        enterpriseName: tem.enterpriseName
      });
  });

  return newAddr;
};

// 确认并保存
const save = async (bol) => {
  let step4Form = await refStep4.value.getData();
  let contractNumList = await getContractNum(
    userList.value.map(({ id }) => {
      return { userId: id, id: temList.value[0].typeId };
    })
  );

  // console.log('判断是1还是2就添加本地合同', formData);

  let contractList = await userList.value.map((user, index) => {
    return {
      ...formData,
      ...step4Form,
      userId: user.id,
      contractName: user.name + '的合同',
      status: 1,
      isChang: 2,
      contractNum: contractNumList[index],
      remindTime: countRemindDate(step4Form.signature, step4Form.remind),
      // children: []
      children: getTemList(user)
    };
  });
  // 判断是1还是2就添加本地合同
  contractList.forEach((item) => {
    if (formData.contractTemplateType === 1) {
      // 判断是旧文件还是新文件
      let data = {
        id: item.uploadContract[0].id || item.uploadContract[0].id || 0,
        fileName:
          item.uploadContract[0].response.useFileName ||
          item.uploadContract[0].response.fileName,
        fileUrl:
          item.uploadContract[0].response.DownloadPath ||
          item.uploadContract[0].response.fileUrl
      };
      item.uploadContract = data;
      // console.log('进来了data', item.uploadContract);
    } else {
      item.uploadContract = {};
    }
  });
  contractList[0] = { ...contractList[0], id: idData.value };
  console.log(contractList[0]);
  let urlData = [];
  // 判断是修改信息 还是 更换状态
  if (bol) {
    console.log('修改信息，该状态');
    // 修改起草合同(确认并保存)
    // 发起起草合同同时修改状态
    urlData = [
      DraftWaitSignedContractSavePut(contractList[0]),
      DraftWaitSignedContractSavePutStatus({
        ids: userList.value.map(({ id }) => id),
        status: 4
      })
    ];
  } else {
    console.log('修改信息');
    urlData = [DraftWaitSignedContractSavePut(contractList[0])];
  }
  await Promise.all(urlData);
  //  await Promise.all([

  //   DraftWaitSignedContractSavePutStatus({
  //     ids: userList.value.map(({ id }) => id),
  //     status: 4
  //   })
  // ]);
  router.back();
};
// 回显信息
let initializedData = async () => {
  const res = await getContractData();
  console.log('回显信息=================================================', res);
  idData.value = res.id;
  // 第一份数据
  let refStep1Data = {};
  if (res.uploadContract.fileUrl) {
    console.log('本地');
    stepData.value = type1;
    refStep1Data = {
      companyId: res.companyId, //合作单位
      contractTemplateType: 1, //合同类型
      templateId: res.children[0].id,
      typeId: res.children[0].typeId,
      uploadContract: [res.uploadContract],
      remark: res.remark //备注
    };
    nextTick(() => {
      refStep1.value.setData(
        refStep1Data,
        userId,
        { id: 0, name: '' },
        res.children
      );
    });
  } else {
    console.log('模版');
    stepData.value = type2;
    refStep1Data = {
      companyId: res.companyId, //合作单位
      contractTemplateType: 2, //合同类型
      templateId: res.children[0].id,
      typeId: res.children[0].typeId,
      remark: res.remark //备注
    };
    let attachment = [];
    // arr.slice(1)
    // 去除主合同只要下标0后面的以为附赠模版在后面
    if (res.children.length != 1) {
      attachment = res.children.slice(1);
    }
    nextTick(() => {
      refStep1.value.setData(refStep1Data, userId, res.children[0], attachment);
    });
  }
  // 第四份数据
  let refStep4Data = {
    overTime: res.overTime, //合同确认截止日期
    expire: res.expire, //通过或者不通过
    signature: res.signature, //有效期
    remind: res.remind //提醒
  };
  nextTick(() => {
    refStep4.value.setData(refStep4Data);
  });
};
initializedData();

// 获取合同编号
const getContractNum = async (list: any[]) => {
  return await Promise.all(list.map((data) => GetGenerateContractNum(data)));
};

// 获取合同预警时间
const countRemindDate = (date: string, num: number) => {
  const tempDay = dayjs(date);
  const result = tempDay.subtract(num, 'day');
  return result.format('YYYY-MM-DD');
};

const changeStepData = (e: any) => {
  e === 1 ? (stepData.value = type1) : (stepData.value = type2);
};
</script>

<style lang="less" scoped>
.template-steps {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}
footer {
  height: 50px;
  padding-top: 15px;
  width: calc(100% - 220px);
  background-color: #fff;
  box-shadow: 0px 0px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 220px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  z-index: 600;
}
</style>
